const Router = require('koa-router')
const db = require('../db')
const cache = require('../middleware/cache')

const router = new Router({ prefix: '/api/home' })

// 首页接口使用缓存中间件，缓存时间60秒
router.get('/', cache({ expire: 60 }), async (ctx) => {
  try {
    const { page = 1, limit = 6, category, teacher, time, keyword } = ctx.query
    
    let conditions = ['1=1']
    
    // 查询轮播图 - 只返回is_show=1的轮播图
    const banners = await db.query('SELECT * FROM banners WHERE is_show = 1 ORDER BY sort DESC')
    
    // 构建查询条件
    if (keyword && keyword !== 'undefined' && keyword.trim()) {
      conditions.push(`(c.title LIKE '%${keyword.trim()}%' OR c.description LIKE '%${keyword.trim()}%')`)
    }
    
    if (category && category !== 'undefined') {
      conditions.push(`c.category_id = ${category}`)
    }
    
    if (teacher && teacher !== 'undefined') {
      conditions.push(`c.teacher_id = ${teacher}`)
    }
    
    // 在构建查询条件部分添加时间筛选
    if (time && time !== 'undefined') {
      conditions.push(`c.time_type = '${time}'`)
    }

    const offset = (parseInt(page) - 1) * parseInt(limit)
    
    // 查询课程列表
    const recommendCourses = await db.query(`
      SELECT 
        c.*, 
        c.time_type,
        t.name as teacher_name,
        t.avatar as teacher_avatar,
        t.title as teacher_title,
        t.description as teacher_description,
        (SELECT COUNT(*) FROM course_schedules WHERE course_id = c.id) as chapter_count
      FROM courses c
      LEFT JOIN teachers t ON c.teacher_id = t.id
      WHERE ${conditions.join(' AND ')}
      ORDER BY c.enroll_count DESC 
      LIMIT ${parseInt(limit)} OFFSET ${offset}
    `)
    
    // 查询分类
    const categories = await db.query('SELECT * FROM categories ORDER BY sort')

    ctx.body = {
      code: 200,
      data: { 
        banners, 
        recommendCourses, 
        categories,
        pagination: {
          current: parseInt(page),
          pageSize: parseInt(limit)
        }
      }
    }
  } catch (err) {
    console.error('首页数据获取错误:', err)
    ctx.status = 500
    ctx.body = {
      code: 500,
      message: '服务器内部错误',
      error: err.message
    }
  }
})

module.exports = router